<template>
  <div class="category-page">
    <Header :isSearch="true" @search="onSearch" />
    <!-- 顶部横幅 -->
    <div class="banner" v-if="!isMobile">
      <img src="@/assets/images/category/cate-banner.png" alt="茶艺展示" class="banner-image" />
    </div>

    <!-- 产品系列标题 -->
    <template v-if="!isMobile">
      <div class="section-title container">
        <h2>产品系列</h2>
        <div class="en-title">PRODUCT SERIES</div>
        <div class="title-line"></div>
      </div>

      <!-- 产品列表 -->
      <div class="product-list container">
        <div class="sidebar">
          <h4 class="sidebar-title" style="cursor: pointer" @click="switchCategories(-1)">全部系列</h4>
          <ul class="category-menu">
            <li v-for="(category, index) in productCategories" :key="index" @click="switchCategories(index)" :class="{ active: tabIndex === index }">
              {{ category.group_name }}
            </li>
          </ul>
        </div>

        <div class="product-grid" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
          <div class="product-item" v-for="(product, index) in dataList" :key="index" @click="toDetail(product)">
            <div class="product-image">
              <img :src="proxy.$buildUrl(product.white_back_ground_pic_url)" :alt="product.spu_name" />
            </div>
            <div class="product-info">
              <div class="product-title">{{ product.spu_name }}</div>
              <div class="product-meta">
                <span class="product-sales">规格: {{ product.sku_name }}</span>
                <span class="product-price">¥{{ product.price_min }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- <div v-if="loading" class="loading-text">加载中...</div>
        <div v-if="noMore" class="no-more-text">没有更多了</div> -->

        <!-- 右侧工具栏 -->
        <div class="side-tools">
          <div class="tool-item">
            <i class="el-icon-service"></i>
          </div>
          <div class="tool-item" @click="toCart">
            <i class="el-icon-shopping-cart-full"></i>
          </div>
          <div class="tool-item" @click="toUser">
            <i class="el-icon-star-off"></i>
          </div>
          <div class="tool-item" @click="toTop">
            <i class="el-icon-top"></i>
          </div>
        </div>
      </div>
    </template>
    <template v-else>
      <div class="mobile-wrap">
        <div class="mobile-category">
          <span
            v-for="(category, index) in productCategories"
            :key="index"
            @click="switchCategories(index)"
            :class="{ active: tabIndex === index }"
            >{{ category.group_name }}</span
          >
        </div>
        <div class="right-wrap">
          <div class="banner">
            <img src="@/assets/images/category/cate-banner.png" alt="茶艺展示" class="banner-image" />
          </div>
          <div class="product-grid" v-infinite-scroll="loadMore" :infinite-scroll-disabled="disabled">
            <div class="product-item" v-for="(product, index) in dataList" :key="index" @click="toDetail(product)">
              <div class="product-image">
                <img :src="proxy.$buildUrl(product.white_back_ground_pic_url)" :alt="product.spu_name" />
              </div>
              <div class="product-info">
                <div class="product-title">{{ product.spu_name }}</div>
                <div class="product-meta">
                  <span class="product-sales">规格: {{ product.sku_name }}</span>
                  <span class="product-price">¥{{ product.price_min }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- <div v-if="loading" class="loading-text">加载中...</div>
          <div v-if="noMore" class="no-more-text">没有更多了</div> -->
        </div>
      </div>
    </template>

    <BottomNavbar v-if="isMobile" />
    <!-- 页脚 -->
    <Footer v-if="!isMobile" />
  </div>
</template>

<script setup>
  import { getCurrentInstance, ref, onMounted, onUnmounted, computed } from 'vue'
  import Footer from '@/components/Footer.vue'
  import Header from '@/components/Header.vue'
  import BottomNavbar from '@/components/BottomNavbar.vue'
  import apiGood from '@/api/modules/good'
  import { useRouter, useRoute } from 'vue-router'

  const router = useRouter()
  const route = useRoute()
  const { proxy } = getCurrentInstance()
  const groupId = ref(route.query.id ? route.query.id : '')
  const keyword = ref(route.query.keyword ? route.query.keyword : '')

  const isMobile = ref(false)
  const deviceInfo = ref({
    type: '',
    os: '',
    browser: '',
    screenWidth: 0,
  })

  const getDeviceInfo = () => {
    const userAgent = navigator.userAgent.toLowerCase()
    const screenWidth = window.innerWidth

    // 检测操作系统
    let os = 'Unknown'
    if (userAgent.includes('android')) os = 'Android'
    else if (userAgent.includes('iphone') || userAgent.includes('ipad')) os = 'iOS'
    else if (userAgent.includes('windows')) os = 'Windows'
    else if (userAgent.includes('mac')) os = 'macOS'
    else if (userAgent.includes('linux')) os = 'Linux'

    // 检测浏览器
    let browser = 'Unknown'
    if (userAgent.includes('chrome')) browser = 'Chrome'
    else if (userAgent.includes('firefox')) browser = 'Firefox'
    else if (userAgent.includes('safari')) browser = 'Safari'
    else if (userAgent.includes('edge')) browser = 'Edge'

    // 检测设备类型
    let type = 'Desktop'
    if (userAgent.includes('mobile') || screenWidth <= 768) type = 'Mobile'
    else if (userAgent.includes('tablet') || (screenWidth > 768 && screenWidth <= 1024)) type = 'Tablet'

    deviceInfo.value = { type, os, browser, screenWidth }

    return { type, os, browser, screenWidth }
  }

  // 检测是否为移动设备
  const checkMobile = () => {
    const { type, screenWidth } = getDeviceInfo()
    const userAgent = navigator.userAgent.toLowerCase()

    // 更精确的移动设备检测
    const mobileKeywords = ['mobile', 'android', 'iphone', 'ipod', 'blackberry', 'windows phone']
    const tabletKeywords = ['ipad', 'tablet']

    const isMobileDevice = mobileKeywords.some((keyword) => userAgent.includes(keyword))
    const isTabletDevice = tabletKeywords.some((keyword) => userAgent.includes(keyword))
    const isSmallScreen = screenWidth <= 768
    const isMediumScreen = screenWidth > 768 && screenWidth <= 1024

    // 移动设备或小屏幕显示移动端界面
    // 平板设备根据屏幕宽度决定
    isMobile.value = isMobileDevice || isSmallScreen || (isTabletDevice && isMediumScreen)
  }
  checkMobile()

  const toDetail = (product) => {
    // window.scrollTo(0, 0)
    // router.push({
    //   path: '/detail',
    //   query: {
    //     id: product?.id,
    //   },
    // })

    // 先通过路由器的resolve方法解析出目标路由的URL
    const route = router.resolve({ path: '/detail', query: { id: product?.id } })
    // 然后使用window.open打开新窗口
    window.open(route.href, '_blank')
  }

  const toCart = () => {
    window.scrollTo(0, 0)
    router.push({
      path: '/cart',
    })
  }

  const toTop = () => {
    // 滚动到顶部
    window.scrollTo(0, 0)
  }

  const toUser = () => {
    // 直接跳转到用户中心，让路由守卫处理登录检查
    router.push('/user')
  }

  // 产品分类数据
  const tabIndex = ref(-1)
  const productCategories = ref([])
  // 产品数据分页查询
  const recordCount = ref(0)
  const page = ref(1)
  const limit = ref(6)
  const dataList = ref([])

  // 是否正在加载
  const loading = ref(false)
  // 是否还有更多数据
  const hasMore = ref(true)
  // 计算属性 - 是否禁用无限滚动
  const disabled = computed(() => loading.value || !hasMore.value)
  // 计算属性 - 是否没有更多数据
  const noMore = computed(() => !hasMore.value && dataList.value.length > 0)

  // 分页加载数据
  const fetchData = async (currentPage) => {
    if (loading.value) {
      return
    }
    loading.value = true
    console.log('分页加载数据', currentPage)
    apiGood
      .GetProductList({ page: currentPage, limit: limit.value, keyword: keyword.value, group_id: groupId.value })
      .then(async (res) => {
        loading.value = false
        recordCount.value = res.count
        page.value = currentPage
        hasMore.value = currentPage * limit.value < recordCount.value
        if (page.value === 1) {
          dataList.value = res.data
        } else {
          dataList.value = [...dataList.value, ...res.data]
        }
      })
      .catch((err) => {
        loading.value = false
      })
  }

  // 加载更多数据
  const loadMore = () => {
    if (!disabled.value) {
      fetchData(page.value + 1)
    }
  }

  function loadProductGroup() {
    apiGood.GetProductGroup().then(async (res) => {
      productCategories.value = res.data
      const index = productCategories.value.findIndex((item) => item.id === groupId.value)
      if (index >= 0) {
        switchCategories(index)
      } else {
        fetchData(1)
      }
    })
  }

  // 组件挂载时获取数据
  onMounted(async () => {
    loadProductGroup()
  })

  function switchCategories(index) {
    tabIndex.value = index
    if (index >= 0) {
      groupId.value = productCategories.value[index].id
    } else {
      groupId.value = ''
    }
    fetchData(1)
  }

  function onSearch(searchQuery) {
    console.log('搜索内容:', searchQuery)
    keyword.value = searchQuery
    tabIndex.value = -1
    groupId.value = ''
    fetchData(1)
  }
</script>

<style scoped>
  .category-page {
    max-width: 1200px;
    margin: auto;
    width: 100%;
  }

  /* 横幅样式 */
  .banner {
    width: 100%;
    height: 600px;
    overflow: hidden;
    position: relative;
  }

  .banner-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  /* 产品系列标题 */
  .section-title {
    text-align: left;
    margin: 40px auto;
    position: relative;
    padding: 0 20px;
  }

  .section-title h2 {
    font-size: 28px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 600;
  }

  .en-title {
    font-size: 16px;
    color: #999;
    text-transform: uppercase;
    letter-spacing: 1px;
  }

  .title-line {
    width: 100%;
    height: 2px;
    background-color: #52a58a;
    margin-top: 15px;
  }

  /* 产品列表区域 */
  .product-list {
    display: flex;
    margin: 40px auto;
    position: relative;
    padding: 0 20px;
    gap: 40px;
  }

  /* 侧边栏 */
  .sidebar {
    width: 220px;
    flex-shrink: 0;
  }

  .sidebar-title {
    font-size: 18px;
    color: #333;
    margin: 0 0 20px 0;
    padding: 0 0 10px 0;
    border-bottom: 2px solid #52a58a;
    font-weight: 600;
  }

  .category-menu {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  .category-menu li {
    padding: 15px 20px;
    cursor: pointer;
    transition: all 0.3s;
    color: #666;
    border-radius: 8px;
    margin-bottom: 5px;
    font-size: 15px;
  }

  .category-menu li:last-child {
    border-bottom: none;
  }

  .category-menu li:hover,
  .category-menu li.active {
    color: #52a58a;
    background-color: #f0f8f5;
    transform: translateX(5px);
  }

  /* 产品网格 */
  .product-grid {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 25px;
  }

  .product-item {
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s;
    background: white;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    cursor: pointer;
    max-height: 350px;
  }

  .product-item:hover {
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    transform: translateY(-8px);
  }

  .product-image {
    width: 100%;
    height: 220px;
    overflow: hidden;
    position: relative;
  }

  .product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.5s;
  }

  .product-item:hover .product-image img {
    transform: scale(1.08);
  }

  .product-info {
    padding: 20px;
  }

  .product-title {
    font-size: 17px;
    color: #333;
    margin-bottom: 12px;
    line-height: 1.4;
    font-weight: 500;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .product-price {
    color: #52a58a;
    font-size: 18px;
    font-weight: 600;
  }

  .product-sales {
    color: #999;
    font-size: 13px;
  }

  /* 右侧工具栏 */
  .side-tools {
    position: fixed;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    z-index: 100;
  }

  .tool-item {
    width: 40px;
    height: 40px;
    background-color: #fff;
    border: 1px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 5px;
    cursor: pointer;
    transition: all 0.3s;
  }

  .tool-item:hover {
    background-color: #1e8e3e;
    color: white;
  }

  .tool-item i {
    font-size: 20px;
  }

  /* 响应式调整 */
  @media (max-width: 1024px) {
    .category-page {
      padding: 0 15px;
    }

    .section-title {
      margin: 30px auto;
      padding: 0 10px;
    }

    .section-title h2 {
      font-size: 24px;
    }

    .product-list {
      gap: 30px;
      padding: 0 10px;
    }

    .sidebar {
      width: 200px;
    }

    .product-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      margin-top: 20px;
    }

    .product-image {
      height: 120px;
    }

    .side-tools {
      right: 10px;
    }
  }

  @media (max-width: 768px) {
    .category-page {
      padding: 0;
    }

    .banner {
      height: 120px;
    }

    .section-title {
      margin: 25px auto;
      padding: 0 20px;
      text-align: center;
    }

    .section-title h2 {
      font-size: 22px;
    }

    .en-title {
      font-size: 14px;
    }

    .product-list {
      flex-direction: column;
      gap: 25px;
      margin: 30px auto;
      padding: 0 20px;
    }

    .sidebar {
      width: 100%;
    }

    .sidebar-title {
      text-align: center;
      font-size: 16px;
      margin-bottom: 15px;
    }

    .category-menu {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 8px;
    }

    .category-menu li {
      padding: 12px 15px;
      text-align: center;
      border-radius: 6px;
      margin-bottom: 0;
      font-size: 14px;
      border: 1px solid #e0e0e0;
    }

    .category-menu li:hover,
    .category-menu li.active {
      transform: none;
      border-color: #52a58a;
    }

    .product-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 15px;
    }

    .product-item {
      border-radius: 10px;
    }

    .product-image {
      height: 120px;
    }

    .product-info {
      padding: 15px;
    }

    .product-title {
      font-size: 15px;
      margin-bottom: 10px;
    }

    .product-price {
      font-size: 16px;
    }

    .product-sales {
      font-size: 12px;
    }

    /* 移动端隐藏右侧工具栏 */
    .side-tools {
      display: none;
    }

    .banner-image {
      height: 120px;
    }
  }

  @media (max-width: 480px) {
    .banner {
      height: 120px;
    }

    .section-title {
      margin: 20px auto;
      padding: 0 15px;
    }

    .section-title h2 {
      font-size: 20px;
    }

    .en-title {
      font-size: 13px;
    }

    .product-list {
      margin: 25px auto;
      padding: 0 15px;
      gap: 20px;
    }

    .sidebar-title {
      font-size: 15px;
      margin-bottom: 12px;
    }

    .category-menu {
      grid-template-columns: 1fr;
      gap: 6px;
    }

    .category-menu li {
      padding: 10px 12px;
      font-size: 13px;
    }

    .product-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 10px;
    }

    .product-item {
      border-radius: 8px;
      max-width: 100%;
    }

    .product-image {
      height: 120px;
    }

    .product-info {
      padding: 12px;
    }

    .product-title {
      font-size: 14px;
      margin-bottom: 8px;
    }

    .product-meta {
      flex-direction: column;
      align-items: flex-start;
      gap: 5px;
    }

    .product-price {
      font-size: 15px;
    }

    .product-sales {
      font-size: 11px;
    }

    .banner-image {
      height: 120px;
    }
  }

  .mobile-wrap {
    display: flex;
    align-items: flex-start;
    justify-content: flex-start;
  }

  .mobile-category {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-direction: column;
    width: 80px;
    background: #f7f7f7;
    height: calc(100vh - 180px);
    overflow-y: auto;

    span {
      line-height: 35px;
      text-align: center;
      width: 100%;
      font-size: 12px;
      padding: 3px;
      color: #666;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .active {
      background: #fff;
      color: #0c5460;
      border-left: 2px solid #0c5460;
    }
  }

  .right-wrap {
    flex: 1;
    padding: 20px;
    height: calc(100vh - 180px);
    overflow-y: scroll;
  }

  /* 加载更多 */
  .loading-text,
  .no-more-text {
    width: 100%;
    height: 30px;
    line-height: 30px;
    text-align: center;
    padding: 10px;
    color: #999;
  }
</style>
